package com.xiaowu.system.manager;

import com.xiaowu.common.core.constants.CacheConstants;
import com.xiaowu.common.redis.service.RedisService;
import com.xiaowu.common.redis.service.RedissonLockService;
import com.xiaowu.common.core.constants.CacheLockConstants;
import com.xiaowu.system.domain.exam.Exam;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class ExamCacheManager {

    // 注入RedisService
    @Autowired
    private RedisService redisService;

    @Autowired
    private RedissonLockService redissonLockService;

    // 添加缓存（）
    @Async(value = "threadPoolTaskExecutor")
    public void addCache(Exam exam) {
        // 获取分布式锁
        RLock rLock = redissonLockService.acquire(CacheLockConstants.EXAM_ADD_LOCK, -1);

        // 获取锁失败跳过执行
        if (null == rLock) {
            return;
        }
        try {
            // 新增竞赛缓存
            redisService.leftPushForList(getExamListKey(), exam.getExamId());
            // 新增竞赛详细信息缓存
            redisService.setCacheObject(getDetailKey(exam.getExamId()), exam);
        } catch (Exception e) {
            log.error("缓存竞赛信息失败");
        } finally {
            // 释放锁
            if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
                redissonLockService.releaseLock(rLock);
            }
        }
    }

    // 删除缓存
    @Async(value = "threadPoolTaskExecutor")
    public void deleteCache(Long examId) {
        // 获取分布式锁
        RLock rLock = redissonLockService.acquire(CacheLockConstants.EXAM_DEL_LOCK, -1);

        // 获取锁失败跳过执行
        if (null == rLock) {
            return;
        }
        try {
            // 删除竞赛缓存
            redisService.removeForList(getExamListKey(), examId);
            // 删除竞赛详细信息缓存
            redisService.deleteObject(getDetailKey(examId));
            // 删除竞赛题目缓存
            redisService.deleteObject(getExamQuestionListKey(examId));
        } catch (Exception e) {
            log.error("缓存竞赛信息失败");
        } finally {
            // 释放锁
            if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
                redissonLockService.releaseLock(rLock);
            }
        }
    }

    // 获取examListKey
    private String getExamListKey() {
        return CacheConstants.EXAM_UNFINISHED_LIST;
    }

    // 获取examDetailKey
    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }

    // 获取examQuestionListKey
    private String getExamQuestionListKey(Long examId) {
        return CacheConstants.EXAM_QUESTION_LIST + examId;
    }
}
